package com.ygqh.baby.controller.admin;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ygqh.baby.ao.Message;
import com.ygqh.baby.po.YgAttribute;
import com.ygqh.baby.service.YgAttributeService;

@Controller
@RequestMapping("admin/attribute")
public class AttributeController extends BaseController<Object, Long> {

	@Autowired
	private YgAttributeService ygAttributeService;
	
	@RequestMapping(value = "searchAttribute", method = RequestMethod.GET)
	@ResponseBody
	public Message searchAttribute() {
		return Message.success(ygAttributeService.find());
	}

	@RequestMapping(value = "saveAttribute", method = RequestMethod.POST)
	@ResponseBody
	public Message saveAttribute(YgAttribute attribute) {
		if (ygAttributeService.validateAttributeName(attribute.getParentId(), attribute.getAttributeName(), null)) {
			attribute.setId(null);
			attribute.setCreateBy(getSession().getTrueName());
			attribute.setCreateTime(new Date());
			ygAttributeService.save(attribute);
			return Message.success(attribute);
		}
		return Message.error("同级属性下名称重复", null);
	}

	@RequestMapping(value = "renameAttribute", method = RequestMethod.POST)
	@ResponseBody
	public Message renameAttribute(Long id, Long parentId, String attributeName) {
		if (ygAttributeService.validateAttributeName(parentId, attributeName, id)) {
			YgAttribute record = new YgAttribute();
			record.setId(id);
			record.setAttributeName(attributeName);
			record.setUpdateTime(new Date());
			record.setUpdateBy(getSession().getTrueName());
			ygAttributeService.update(record);
			return SUCCESS_MESSAGE;
		}
		return Message.error("同级属性下名称重复", null);
	}

	@RequestMapping(value = "delAttribute", method = RequestMethod.POST)
	@ResponseBody
	public Message delAttribute(Long id) {
		List<YgAttribute> attributeList = ygAttributeService.findByParentId(id);
		if (CollectionUtils.isNotEmpty(attributeList)) {
			return Message.error("该属性下有子级属性", null);
		}
		ygAttributeService.deleteSoft(id);
		return SUCCESS_MESSAGE;
	}

	@RequestMapping(value = "findAttributeByParentId", method = RequestMethod.GET)
	@ResponseBody
	public Message findAttributeByParentId(Long parentId) {
		return Message.success(ygAttributeService.findByParentId(parentId));
	}

}
